package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.config.Result;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.IPaymentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 支付记录管理 前端控制器
 *
 * @author zhenyu
 * @since 2022-07-25
 */
@Api(value = "支付记录管理", tags = "支付记录管理")
@RestController
@RequestMapping("/payment")
@Slf4j
public class Controller {

  @Autowired
  private IPaymentService iPaymentService;

  @Resource
  private DiscoveryClient discoveryClient;

  @Value("${server.port}")
  private String serverPort;  //添加serverPort

  @GetMapping("/getPaymentById/{id}")
  @ApiOperation("查询支付记录")
  public Result<Payment> getPaymentById(@PathVariable("id") Long id)
      throws ParseException {
    return Result.success(iPaymentService.getPaymentById(id), "serverport:" + serverPort);
  }

  @PostMapping("/create")
  @ApiOperation("新增支付记录")
  public Result<String> create(@RequestBody Payment payment) throws ParseException {
    return iPaymentService.create(payment);
  }

  @GetMapping(value = "/discovery")
  public Object discovery(){
    List<String> services = discoveryClient.getServices();
    for (String element : services) {
      log.info("element:"+element);
    }

    List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
    for (ServiceInstance instance : instances) {
      log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
    }
    return this.discoveryClient;
  }

  @GetMapping(value = "/feign/timeout")
  public String paymentFeignTimeout()
  {
    // 业务逻辑处理正确，但是需要耗费3秒钟
    try {
      TimeUnit.SECONDS.sleep(3);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    return serverPort;
  }

  @GetMapping(value = "/lb")
  public String getServerPort()
  {
    return serverPort;
  }

}
